import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
import { getToken, removeToken } from "@/api/token";
//自定义配置新建一个axios实例
const service = axios.create({
  baseURL: "/"
});
axios.withCredentials = true;
axios.default.post["Content-Type"] = "application/json; charset=UTF-8";
axios.default.timeout = 6000 * 5;
axios.paramsSerializer = function(params) {
  return qs.stringify(params, { arrayFormat: "brackets" });
};

const whiteList = [
  "login",
  "messageCode",
  "addUser",
  "updatePwd",
  "getSharesNum",
  "regist"
];

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    // 请求前设置请求头
    // let lastStr = config.url.substring(config.url.lastIndexOf("/") + 1);
    // if (whiteList.indexOf(lastStr) === -1) {
    //   if (!getToken() || JSON.stringify(getToken()) == "{}") {
    //     localStorage.clear();
    //     location.href = "/#/login";
    //   } else {
    //     config.headers["accesstoken"] = getToken();
    //   }
    // }
    if (config.method === "post") {
      // 序列化
      config.data = qs.stringify(config.data);
    }
    return Promise.resolve(config);
  },
  error => {
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  response => {
    let status = response.status;
    if (status === 200) {
      if (response.data.code && response.data.code == 400) {
        localStorage.clear();
        removeToken();
        location.href = "/#/login";
      } else if (!response.data.code) {
        return Promise.resolve(response);
      } else {
        Message({
          message: "服务器访问异常",
          type: "warning",
          duration: 1.5 * 1000
        });
        return Promise.reject(response);
      }
    } else {
      Message({
        message: "服务器访问异常",
        type: "warning",
        duration: 1.5 * 1000
      });
      return Promise.reject(response);
    }
  },
  error => {
    Message({
      message: "服务器访问异常",
      type: "warning",
      duration: 1.5 * 1000
    });
    return Promise.reject(error);
  }
);
export default service; // 记住此处
